<!DOCTYPE HTML>
<!--
	Spectral by HTML5 UP
	html5up.net | @ajlkn
	Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
	<head>
		<title>Image Detect</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
		<link rel="stylesheet" href="assets/css/main.css" />
		<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
		<style>
			#one{
				background-color:rgba(68,0,68,0);
				
			}
			
			#camBlock{
				transform:translate(0px,-25px);
			}
		
			.detection{
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-around;
			}
			.detect-block{
				height:400px;
				width: 400px;
				display: inline;
				background-color: rgba(0,0,0,0);
				display:flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				border-radius: 200px;
			}
			.imgBox{
			border: 5px solid #cccccc;
            margin-top: 10px;
            width:300px;
            height:300px;
            border-radius: 5px;
			}
			.imgBox>span{
				display: block;
				width:100%;
				height: 100%;
				text-align: center;
				line-height:300px;
			}
			.imgUpload{
            display:none;
			}
			.imgBuffer{
				width:100%;
				height:100%;
				
				border-radius: 5px;
				background-size:100% 100%;
			}
			.imgProcess{
            margin-bottom: 10px;
            width:300px;
            height: 300px;
            text-align: center;
            line-height:300px;
			}
			.imgProcess>img{
				width:100%;
				height:100%;   
			}
			#main>button{
            cursor:pointer;
            width:200px;
            height:30px;
            margin:10px;
            border-radius: 5px;
            background-color: purple;
            color:white;
        	}
			.buttons{
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-around;
			}
		</style>
	</head>
	<body class="landing is-preload">

		<!-- Page Wrapper -->
			<div id="page-wrapper">

				<!-- Header -->
					<header id="header" class="alt">
						<h1><a href="index.html">Spectral</a></h1>
						<nav id="nav">
							<ul>
								<li class="special">
									<a href="#menu" class="menuToggle"><span>Menu</span></a>
									<div id="menu">
										<ul>
											<li><a href="index.html">Home</a></li>
											<!--li><a href="generic.html">Generic</a></li-->
											<!--li><a href="elements.html">Elements</a></li-->
											<!--li><a href="#">Sign Up</a></li-->
											<!--li><a href="#">Log In</a></li-->
										</ul>
									</div>
								</li>
							</ul>
						</nav>
					</header>

				<!-- Banner -->
					<section id="banner">
						<div class="inner">
							<h2>Image Detect</h2>
							<p>An Image Detect API<br />
							using MaskRCNN as back end<br />
							crafted by <br/><br/>
							Chi, Mingyuan<br />
							Cui, Zimai<br/>
							Li, Wendi<br/></p>
							<!--ul class="actions special">
								<li><a href="#" class="button primary">Activate</a></li>
							</ul-->
						</div>
						<a href="#one" class="more scrolly">Learn More</a>
					</section>

				<!-- One -->
					<section id="one" class="wrapper style1 special" >
						<div class='detection'>
							<div id='camBlock' class='detect-block'>
								<button id='butcam' onclick="openMedia()">开启摄像头</button>
								<div id='no_cam' class='imgBox'></div>
								<div id='camButtons'>
									
									<button id='but1' style="display: none;"onclick="drawMedia()" >截图</button>
									<button id='but2' style="display: none;"onclick="closeMedia()"  >关闭</button>
									<button id='but3'style="display: none;" onclick="submitMedia()" >submit</button>
								</div>
								
								
							</div>
							<div class='detect-block'>
								<div class='imgProcess imgBox' >
								</div>
							</div>
							<div class='detect-block'>
								<div id='upLoadImg' class='imgBox'>
									<input id = 'imgUpload0' class='imgUpload' type=file >
									<img class='imgBuffer'>
									<span>select your img file</span>
									<button id='submitImg'>submit</button>
								</div>
							</div>
						</div>
						<!--div class="inner">
							<header class="major">
								<h2>Arcu aliquet vel lobortis ata nisl<br />
								eget augue amet aliquet nisl cep donec</h2>
								<p>Aliquam ut ex ut augue consectetur interdum. Donec amet imperdiet eleifend<br />
								fringilla tincidunt. Nullam dui leo Aenean mi ligula, rhoncus ullamcorper.</p>
							</header>
							<ul class="icons major">
								<li><span class="icon fa-gem major style1"><span class="label">Lorem</span></span></li>
								<li><span class="icon fa-heart major style2"><span class="label">Ipsum</span></span></li>
								<li><span class="icon solid fa-code major style3"><span class="label">Dolor</span></span></li>
							</ul>
						</div-->
					</section>



				<!-- Footer -->
					<footer id="footer">

						<div class='major'>
							<p>Chi, Mingyuan</p>
							<p>Cui, Zimai</p>
							<p>Li, Wendi</p>
						</div>
						<ul class="copyright">
							<li>&copy; WalkerChi</li><li>Design: WalkerChi</li>
						</ul>
					</footer>

			</div>

		<!-- Scripts -->
			<script src='https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js'></script>
			<script src="assets/js/jquery.min.js"></script>
			<script src="assets/js/jquery.scrollex.min.js"></script>
			<script src="assets/js/jquery.scrolly.min.js"></script>
			<script src="assets/js/browser.min.js"></script>
			<script src="assets/js/breakpoints.min.js"></script>
			<script src="assets/js/util.js"></script>
			<script src="assets/js/main.js"></script>
			<script>
				$(document).ready(function(){
				$('.imgUpload').click(function(event){
					event.stopPropagation();
				})
					$('.imgBuffer').hide();
				})

				$('#upLoadImg').click(function(){
					$(this).children('span').hide();
					$('.imgBuffer').show();
					$(this).children('.imgUpload')[0].click();
					$('.imgUpload').on('change',function(){
						let files = this.files;
						let length = files.length;
						$.each(files,function(key,value){
							let fileReader = new FileReader();
							let file = files[key];
							fileReader.onload = function(){
								if(key == 0){
									$('.imgBuffer').css('background-image','url('+this.result+')');
								}
								}
							fileReader.readAsDataURL(value);
						})
					})
				})


				$('#submitImg').click(function(){
					$('.imgProcess').html('processing...');
					let reader = new FileReader();
					let files= $("#imgUpload0")[0].files;
					if(files.length>0)
					{
						reader.readAsDataURL(files[0]);
						reader.onload = function(){
							let img_data = this.result;
							$.ajax({
							type: "POST",
							url: "detect/file",
							data: { img: img_data },
							cache: false,
							success: function(data) {
								$('.imgProcess').html('<img src="'+data.img+'">');
							},
							error: function(XMLHttpRequest, textStatus, errorThrown) {
								alter('error')
							}
							});
						}
					}
					else{
						alter('choose a file first');
					}
				})
			</script>
			  <script type="text/javascript">

				// 一堆兼容代码
				window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
				if (navigator.mediaDevices === undefined) {
				navigator.mediaDevices = {};
				}
				if (navigator.mediaDevices.getUserMedia === undefined) {
				navigator.mediaDevices.getUserMedia = function(constraints) {
				 var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
				 if (!getUserMedia) {
				 return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
				 }
				 return new Promise(function(resolve, reject) {
				 getUserMedia.call(navigator, constraints, resolve, reject);
				 });
				}
				} 
		
				//摄像头调用配置
				var mediaOpts = {
				audio: false,
				video: true,
				video: { facingMode: "environment"} // 或者 "user"
				// video: { width: 1280, height: 720 }
				// video: { facingMode: { exact: "environment" } }// 或者 "user"
				}
		
				// var cam = $('#camera')
				// var open_cam = cam.children('open_cam')[0]
				// var snap_shot = cam.children('snap_shot')[0]
				var static_cam = '<canvas id="qr-canvas" class="imgBox"></canvas>'
				var dynam_cam = '<video id="video" class="imgBox"></video>'
				var no_cam = '<div class="imgBox"></div>'
				var cam = $('.detect-block')[0]
		
				var cam_on = 0  // 0 -> No  1-> on  2->static
		
		
				//var video = document.querySelector('video');
				//var text = document.getElementById('text');
				//var canvas1 = document.getElementById('qr-canvas');
				//var context1 = canvas1.getContext('2d');
				var mediaStreamTrack;
				
		
				

				// 回调
				function successFunc(stream) {
				mediaStreamTrack = stream;
				video = document.querySelector('video');
				if ("srcObject" in video) {
				 video.srcObject = stream
				} else {
				 video.src = window.URL && window.URL.createObjectURL(stream) || stream
				}
				video.play();
				}
				function errorFunc(err) {
				 console.log(err);
                }
                
 
				// 正式启动摄像头
				function openMedia(){
					$("#but1").fadeToggle();
					$("#but2").fadeToggle("slow");
					$("#but3").fadeToggle(3000);

				if(cam_on==0){
					var no_cam = document.querySelector("#no_cam");
					no_cam.remove();
					var cam = document.querySelector('#camBlock');
					var video = document.createElement('video');
					video.id = 'video';
					video.setAttribute('class','imgBox');
                    cam.insertBefore(video, cam.childNodes[2]);
                    console.log(mediaOpts);
					navigator.mediaDevices.getUserMedia(mediaOpts).then(successFunc).catch(errorFunc);

				}else if(cam_on == 2){
					var canvas = document.querySelector("#qr-canvas");
					canvas.remove();
					var cam = document.querySelector('#camBlock');
					var video = document.createElement('video');
					video.id = 'video';
					video.setAttribute('class','imgBox');
					cam.insertBefore(video, cam.childNodes[2]);
					navigator.mediaDevices.getUserMedia(mediaOpts).then(successFunc).catch(errorFunc);
				}
				cam_on = 1;
				}
				
				//关闭摄像头
				function closeMedia(){
					if(cam_on == 1){
						var video = document.getElementById('video');
						video.remove()
					
					}else if(cam_on == 2){
						var canvas = document.getElementById('qr-canvas');
						canvas.remove()
					}
					var no_cam = document.createElement('div');
						no_cam.id = 'no_cam';
						no_cam.setAttribute('class','imgBox');
						var cam = document.querySelector('#camBlock')
						cam.insertBefore(no_cam, cam.childNodes[2])
						mediaStreamTrack.getVideoTracks().forEach(function (track) {
						track.stop();
						});
						cam_on = 0;
				}
				
				//截取视频
				function drawMedia(){
					if(cam_on == 1){
		
						var video = document.getElementById('video');
						var cam = document.querySelector('#camBlock')
						var canvas = document.createElement('canvas')
						canvas.id = 'qr-canvas'
						canvas.setAttribute('class', 'imgBox');
						canvas.setAttribute("width", '300px');
						canvas.setAttribute("height", '300px');
						//canvas.setAttribute("width", video.videoWidth);
						//canvas.setAttribute("height", video.videoHeight);
						var context = canvas.getContext('2d');
						context.drawImage(video, 0, 0, canvas.width, canvas.height);
						video.remove()
						cam.insertBefore(canvas, cam.childNodes[2])
						cam_on = 2
					}
				}

				function submitMedia(){
					var canvas = document.getElementById('qr-canvas');
					if(canvas != null){
                        var base64 = canvas.toDataURL('image/jpg');
                        console.log(base64)
						$('.imgProcess').html('processing...');
							
                        let img_data = base64;
                        $.ajax({
                        type: "POST",
                        url: "detect/file",
                        data: { img: img_data },
                        cache: false,
                        success: function(data) {
                            $('.imgProcess').html('<img src="'+data.img+'">');
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            alter('error')
                        }
                        });
							
					}
				}
				
			   </script>
			   <script>
			
				</script>

	</body>
</html>